package com.chilly.utils;

/**
 * Created by Chilly Cui on 2020/12/1.
 */
public class LinkedListUtil {

    /**
     * 遍历单链表
     */
    public static void printLink(ListNode head) {
        ListNode curNode = head;
        while (curNode != null) {
            System.out.print(curNode.val + " ");
            curNode = curNode.next;
        }
        System.out.println();
    }

    /**
     * 单链表增加节点
     */
    public static void addLink(ListNode head, int val) {
        ListNode newNode = new ListNode(val);//创建新节点对象
        if (head == null) {
            head = newNode;
            return;
        }
        ListNode temp = head;
        while (temp.next != null) {//找到当前链表尾结点
            temp = temp.next;
        }
        temp.next = newNode;
    }

    /**
     * 统计链表长度
     */
    public static int length(ListNode head) {
        if (head == null) return 0;
        int cnt = 0;
        while (head != null) {
            cnt++;
            head = head.next;
        }
        return cnt;
    }

}
